import React from 'react';
import { message } from 'antd';

class BaseComponent extends React.PureComponent {
  constructor(props) {
    super(props);
    this.title = '';
    this.state = { selectedRows: [] };
  }

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;

    dispatch({
      type: `${this.namespace}/fetch`,
    });
  }

  // 类型
  handleTabChange = type => {
    const { form, dispatch } = this.props;
    form && form.resetFields();

    dispatch({
      type: `${this.namespace}/fetch`,
      payload: { type },
    });
  }

  // 状态
  handleGroupChange = e => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form && form.resetFields();

    dispatch({
      type: `${this.namespace}/fetch`,
      payload: { status: e.target.value }
    });
  }

  // 多选
  handleSelectRows = rows => {
    this.setState({ selectedRows: rows });
  };

  // 下拉
  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: `${this.namespace}/remove`,
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              this.setState({
                selectedRows: []
              });
              dispatch({
                type: `${this.namespace}/fetch`,
              });

              message.success(`共有${data}条${this.title}删除成功~`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      case 'update':
        dispatch({
          type: `${this.namespace}/update`,
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('更新失败！');
            } else {
              dispatch({
                type: `${this.namespace}/fetch`,
              });

              message.success(`共有${data}条${this.title}更新成功~`);
            }
          }
        });
        break;
      default:
        break;
    }
  };

  // 分页
  handleTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: `${namespace}/fetch`,
      payload: params,
    });
  };
}

export default BaseComponent;